package com.yang.servlet;

import com.yang.pojo.Menu1;
import com.yang.pojo.Menu2;
import com.yang.pojo.Role;
import com.yang.service.MenuService;
import com.yang.service.RoleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/RoleQueryServlet")
public class RoleQueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        RoleService roleService = new RoleService();
        MenuService menuService = new MenuService();
        int roleId = Integer.parseInt(request.getParameter("roleId"));
        try {
            //查询当前的用户信息
            Role role = roleService.findRoleById(roleId);

            //查询当前系统中所有的菜单权限
            ArrayList<Menu1> menu1s = menuService.listAllMenu();

            //查询当前角色拥有的菜单id
            List<Integer> menuIds = roleService.findMenuIdByRoleId(roleId);
            //判断所有菜单中，哪些菜单是当前角色拥有的
            for (int i = 0; i < menu1s.size(); i++) {
                Menu1 menu1 = menu1s.get(i);
                //如果menuIds中包含当前一级菜单的id，说明当前角色具有一级菜单
                //那么如何标识这个一级权限的状态呢？——在Menu1实体类中添加一个标识属性
                if(menuIds.contains(menu1.getMenuId())){
                    menu1.setHaveMenu(true);
                }

                //判断二级权限
                for (int j = 0; j < menu1.getChildMenus().size(); j++) {
                    Menu2 menu2 = menu1.getChildMenus().get(j);
                    if(menuIds.contains(menu2.getMenuId())){
                        menu2.setHaveMenu(true);
                    }
                }
            }

            //说明：通过以上for判断及设置，menu1s中当前角色拥有的菜单haveMenu属性都为true
            request.setAttribute("role",role);
            request.setAttribute("menu1s",menu1s);
            request.getRequestDispatcher("admin_role_modify.jsp").forward(request,response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
